package conn

import (
	"encoding/json"
	"errors"
	log "github.com/sirupsen/logrus"
	"gitee.com/cooge/impush/message"
	"net"
	"strconv"
	"time"
)

type CallConnBreak func(*HTCPconn)

type HTCPconn struct {
	conn     *net.TCPConn
	liveTime int
	callConnBreak CallConnBreak
	InTime time.Time
	userId string
}

func NewHTCPconn(conn *net.TCPConn,dealTime int,userId string)*HTCPconn  {
	var htcp HTCPconn
	htcp.conn = conn
	htcp.liveTime = dealTime
	htcp.SetReadDeadline()
	htcp.InTime = time.Now()
	htcp.userId = userId
	return &htcp

}

func (this *HTCPconn) SetReadDeadline()  {
	this.conn.SetReadDeadline(time.Now().Add(time.Duration(this.liveTime+this.liveTime+20) * time.Second))
}

func (this *HTCPconn) IsExpire() bool {
	return this.InTime.Add(time.Duration(this.liveTime) * time.Second).Before(time.Now())
}

func (this *HTCPconn) Close()  {
	this.write([]byte(`[{"Body":"{}","From":"SYSTEM"}]`))
}

func (this *HTCPconn) SendMessage(msg *message.Message) (int, error) {
	var msgs = []*message.Message{msg}
	return this.SendMessages(msgs)
}

func (this *HTCPconn) SendMessages(msgs []*message.Message) (int, error) {
	data_ := make([]interface{}, 0)
	for _, v := range msgs {
		dat := make(map[string]interface{})
		dat[message.FROM] = v.Heads.Get(message.FROM)
		dat[message.BODY] = string(v.Body)
		data_ = append(data_, dat)
	}
	data, err := json.Marshal(&data_)
	if err == nil {
		return this.write(data)
	}
	return 0, errors.New(message.SEND_FAIL)
}

func (this *HTCPconn) Start(callConnBreak CallConnBreak)  {
	this.callConnBreak = callConnBreak
	go this.read()
}

func (this *HTCPconn) GetUser() string {
	return this.conn.RemoteAddr().String()
}

func (this *HTCPconn) write(data []byte) (int, error) {
	this.callConnBreak(this)
	ln := len(data)
	var header string = "HTTP/1.1 200 OK\r\n" +
		"Content-Type: text/html;charset=UTF-8\r\n" +
		"Content-Language: zh\r\n" +
		"Access-Control-Allow-Origin: *\r\n" +
		"Content-Length: " + strconv.Itoa(ln) + "\r\n\r\n"
	da := make([]byte, 0)
	buf := []byte(header)
	da = append(da, buf...)
	da = append(da, data...)
	if this.conn != nil {
		ll, err := this.conn.Write(da)
		if err == nil {
			this.conn.Close()
			return ll, nil
		} else {
			this.conn.Close()
			return 0, err
		}
	}
	this.conn.Close()
	return 0, errors.New("用户已断开")
}
func (this *HTCPconn) read() {
	da := make([]byte, 1)
	_, err := this.conn.Read(da)
	if err != nil {
		log.Debug(this.userId,"连接断开", err)
	}
	this.conn.Close()
	this.callConnBreak(this)
}
